package com.neolix.watch.bluetooth;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.neolix.watch.NeolixApplication;
import com.neolix.watch.NeolixBaseActivity;
import com.neolix.watch.R;
import com.neolix.watch.util.CommonHelper;
import com.neolix.watch.util.Constant;
import com.neolix.watch.util.StringUtil;
import com.neolix.watch.view.ConfirmDialog;

public class BluetoothConnectActivity extends NeolixBaseActivity {

    public BluetoothConnectActivity() {
        super(R.layout.activity_bluetooth_connect);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String address = getIntent().getStringExtra(Constant.DEVICE_NAME);

        registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
        if (StringUtil.isNotBlank(address)) {
            //连接设备
            CommonHelper.showRequestDialog(BluetoothConnectActivity.this, "正在连接");
            NeolixApplication.getInstance().bluetoothLeService.connect(address);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mGattUpdateReceiver);
    }

    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
                //设备连接成功 返回
                CommonHelper.hideRequestDialog();
                BluetoothConnectActivity.this.setResult(RESULT_OK);
                finish();
                Log.i(Constant.BLUETOOTH_TAG, "bluetooth device connected");
            } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
                //设备连接失败
                // TODO 更新UI
                CommonHelper.hideRequestDialog();
                Log.i(Constant.BLUETOOTH_TAG, "bluetooth device disconnected");
            }
        }
    };

    private IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
        return intentFilter;
    }
}
